let dbm = require('../db/index.js');

var user = dbm.user;
let user_model = {
	async list() {
		let rs = user.find({},{_id:0,limit:5},(err,res)=>{
			if (err) {
				return {status:400,msg:"查询失败"};
			} else {
				return res;
			}
		});
		let result = await rs.then(v=>{
			if (v== null) {
				return {status:200,data:[]};
			} else {
				return {status:200,data:v}
			}
		});
		return result;
	},
	async login(info) {
		var rs = user.findOne({username:info['username'],password:md5(info['password'])},{_id:0},(error,result)=>{
			return result;
		});

		var result = await rs.then(v=> {
			if (v == null) {
				return {status:400,msg:"登陆失败"};
			}
			if (v.pid != undefined) {
				return {status:200,msg:'登陆成功',data:{pid:v.pid}};
			} else {
				return {status:400,msg:"登陆失败"};
			}
		});

		return result;
	},

	async reg(info){
		var rs = user.findOne({username:info['username']},(error,result)=>{
			return result;
		});

		let result = await rs.then(v=>{
			if (v == null) {
				console.log('没有用户' + user);
				var rs = user.insert(info,(error,result)=>{
					return result;
				});
				return rs.then(v=>{
					var pid = v['_id'];
					var objId = dbm.ObjId(pid);
					user.update({_id:objId},{$set:{pid}},(error,result)=>{
						console.log(result);
					});
					return {status:200,msg:'注册成功',data:v};
				},
				e=>{
					return {status:400,msg:'注册失败' + e};
				});

			} else {
				return {status:400,msg:'用户已经存在'}
			}
		});

		return result;
	},

	async queryprofile(pid){
		if (pid == null) {
			return {status:400,msg:"pid 不能为空"};
		}
		var rs = user.findOne({pid},{_id:0},(error,result)=>{
			return result;
		});

		let result = await rs.then(v=>{
			return {status:200,msg:"查询成功",data:v};
		});

		return result;
	},

	async updateprofile(info){
		var rs = user.findOne({pid:info['pid']},{_id:0},(error,result)=>{
			return result;
		});
		return res;
	},
}

module.exports = user_model;